package com.boot.web.exception;

import com.boot.web.http.HttpModel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author 霜寒 <1621856595@qq.com>
 * @description 业务异常处理
 * @date 2021/7/8 17:06
 **/

@Order(-1)
@Component
@Slf4j
public class BootHandlerExceptionResolver implements HandlerExceptionResolver {

    private final ExceptionHandlerManager manager;
    private final ObjectMapper om;

    public BootHandlerExceptionResolver(ExceptionHandlerManager manager, ObjectMapper om) {
        this.manager = manager;
        this.om = om;
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.info("================================ Boot Handle Exception =====================================");
        log.warn("Exception      : {}", ex.toString());
        log.warn("message        : {}", ex.getMessage());
        if (log.isDebugEnabled()) {
            ex.printStackTrace();
        }
        ResponseEntity<HttpModel<Object>> entity = null;
        for (ModuleExceptionHandler moduleHandler : manager.getHandlers()) {
            if (moduleHandler.support(ex)) {
                entity = moduleHandler.handle(ex);
            }
        }
        if (null != entity) {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(entity.getStatusCodeValue());
            for (Map.Entry<String, List<String>> entry : entity.getHeaders().entrySet()) {
                response.setHeader(entry.getKey(), String.join(",", entry.getValue()));
            }

            if (entity.getBody() != null) {
                String body;
                try {
                    body = om.writeValueAsString(entity.getBody());
                } catch (JsonProcessingException e) {
                    if (log.isDebugEnabled()) {
                        ex.printStackTrace();
                    }
                    body = "{\"msg\":\"JSON 转换 ResponseEntity.getBody 失败\"}";
                }
                try {
                    response.getWriter().print(body);
                    return new ModelAndView();
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        ex.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
